use anyhow::Result;
use chrono::offset::TimeZone;
use chrono::Utc;
use clap::Clap;
use plotters::prelude::*;
use std::io::BufRead;

#[derive(Clap)]
#[clap(version = "1.0", author = "Donggu Kang")]
struct Opts {
    #[clap(long)]
    r#in: String,
    #[clap(long)]
    out: String,
}

fn main() -> Result<()> {
    let opts = Opts::parse();

    let root = BitMapBackend::new(&opts.out, (640, 480)).into_drawing_area();
    root.fill(&WHITE)?;

    let f = std::io::BufReader::new(std::fs::File::open(opts.r#in)?);

    let points: Vec<(_, u64)> = f
        .lines()
        .skip(1000)
        .map(|line| {
            let line = line.unwrap();
            let fields: Vec<&str> = line.split(" ").collect::<Vec<&str>>();
            let et = fields[2].parse::<i64>().unwrap();
            // let rt = fields[5].parse::<i64>().unwrap();
            // let ft = fields[8].parse::<i64>().unwrap();
            let ft = chrono::DateTime::parse_from_rfc3339(fields[7]).unwrap();
            let ft = ft.timestamp() * 1_000_000_000 + ft.timestamp_subsec_nanos() as i64;

            // let msg = fields[10];
            let ft_datetime = Utc.timestamp(ft / 1_000_000_000, (ft % 1_000_000_000) as u32);
            (ft_datetime, (ft - et) as u64)
        })
        .collect();

    let x_range = points[0].0..points[points.len() - 1].0;
    let y_range = plotters::data::fitting_range(points.iter().map(|pair| &pair.1));

    println!("xrange {:?}", x_range);
    println!("yrange {:?}", y_range);

    let mut chart = ChartBuilder::on(&root)
        .caption("y=x^2", ("sans-serif", 50).into_font())
        .margin(5)
        .x_label_area_size(30)
        .y_label_area_size(80)
        .build_ranged(x_range, y_range)?;

    chart.draw_series(LineSeries::new(points, &RED))?;
    chart.configure_mesh().draw()?;
    Ok(())
}
